<template>
  <el-card class="spu-card">
    <el-form label-width="100px" ref="spuFromRef" :model="spuFormDate" :rules="SpuRules">
      <el-form-item label="SPU名称" prop="spuName">
        <el-input placeholder="SPU名称" v-model="spuFormDate.spuName" />
      </el-form-item>
      <el-form-item label="品牌" prop="tmId">
        <el-select placeholder="请选择品牌" v-model="spuFormDate.tmId">
          <el-option v-for="tm in tradermakList" :key="tm.id" :label="tm.tmName" :value="tm.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input placeholder="SPU描述" :rows="2" type="textarea" v-model="spuFormDate.description" />
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          v-model="spuFormDate.spuImageList"
          v-model:file-list="spuFormDate.spuImageList"
          :action="UPLOAD_URL_PREFIX + `/admin/product/fileUpload`"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload"
          :limit="MAX_LIMIT"
          :on-success="handleSuccess"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </template>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select :placeholder="`还剩${filterSaleAttrList.length}个未选择`" v-model="selectedSaleAttr">
          <el-option v-for="attr in filterSaleAttrList" :key="attr.id" :label="attr.name" :value="`${attr.id}:${attr.name}`" />/
        </el-select>
        <el-button type="primary" :icon="Plus" class="spu-btn" @click="AddSaleAttr" :disabled="!selectedSaleAttr"> 添加销售属性 </el-button>

        <el-table :data="spuFormDate.spuSaleAttrList" border class="spu-table">
          <el-table-column label="序号" type="index" align="center" width="60" />
          <el-table-column label="属性名" prop="saleAttrName" width="200" />
          <el-table-column label="属性值名称列表" prop="xxx">
            <template v-slot="{ row }">
              <el-tag
                closable
                v-for="(saleAttrValue, index) in row.spuSaleAttrValueList"
                :key="saleAttrValue.saleAttrValueName"
                @close="delSaleAttrValue(row, index)"
                >{{ saleAttrValue.saleAttrValueName }}</el-tag
              >
              <el-input
                v-if="row.isEdit"
                ref="inputRef"
                v-model="AddSaleAttrValueName"
                @blur="AddSaleAttrValue(row)"
                @keyup.enter="AddSaleAttrValue(row)"
              ></el-input>
              <el-button :icon="Plus" v-else @click="isEdit(row)"></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <el-tooltip content="删除销售属性" placement="top" effect="light">
              <template v-slot="{ $index }">
                <el-button type="danger" :icon="Delete" size="small" @click="delSaleAttr($index)" />
              </template>
            </el-tooltip>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="goSpuList">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "SaveOrUpdateSqu",
};
</script>

<script lang="ts" setup>
import { Delete, Plus } from "@element-plus/icons-vue";
import { getBaseSaleAttrApi, saveSpuApi, getSpuImageListApi, getSpuSaleAttrListApi } from "@/api/product/spu";
import { getAllTrademarkListApi } from "@/api/product/trademark";
import { computed, onMounted, reactive, ref } from "@vue/runtime-core";
import type { TrademarkList } from "@/api/product/model/trademarkModel";
import type { BaseSaleAttrListModel, spuFormDateType, spuSaleAttrList, SaveSpuSaleAttrItem } from "@/api/product/model/spuModel";
import type { FormRules, UploadProps, FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { nextTick } from "vue";
import { useCategoryStore } from "@/stores/category";
import { map } from "lodash";

const tradermakList = ref<TrademarkList>([]);
const SaleAttrList = ref<BaseSaleAttrListModel>([]);
const SpuImageList = ref();
onMounted(async () => {
  tradermakList.value = await getAllTrademarkListApi();
});
onMounted(async () => {
  SaleAttrList.value = await getBaseSaleAttrApi();
});
//点击修改sku获取图片
onMounted(async () => {
  const { id } = spuFormDate;
  if (!id) return;
  const res = await getSpuImageListApi(id);
  spuFormDate.spuImageList = res.map((img) => {
    return {
      name: img.imgName,
      url: img.imgUrl,
    };
  });
});
//获取销售属性
onMounted(async () => {
  const { id } = spuFormDate;
  if (!id) return;
  spuFormDate.spuSaleAttrList = await getSpuSaleAttrListApi(id);
});

const props = defineProps<{
  spu: spuFormDateType;
}>();
// 表单数据
const spuFromRef = ref<FormInstance>();
const spuFormDate = reactive<spuFormDateType>(props.spu);
// spuName: "",
// tmId: undefined,
// description: "",
// spuImageList: [],
// spuSaleAttrList: [],

//上传图片
// 请求前缀
const UPLOAD_URL_PREFIX = import.meta.env.VITE_API_URL;
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imgType = ["image/jpeg", "image/jpg", "image/png", "image/jpeg"];
  if (!imgType.includes(rawFile.type)) {
    ElMessage.error("上传的图片必须是jpg或png格式!");
    return false;
  } else if (rawFile.size / 1024 > 500) {
    ElMessage.error("上传的图片不能超过500kb!");
    return false;
  }
  return true;
};

// 上传成功的回调
const handleSuccess = () => {
  if (spuFormDate.spuImageList.length === 1) {
    spuFromRef.value?.clearValidate(["spuImageList"]);
  }
};

const spuSaleAttrListValidator = (rule: any, value: spuSaleAttrList, callback: any) => {
  if (!value.length) {
    // value 校验表单的数据
    //callback() //代表校验通过
    // console.log(value);
    callback(new Error("至少添加一个属性"));
    return;
  }
  if (!value.every((item) => item.spuSaleAttrValueList.length)) {
    // console.log(item);
    callback(new Error("每个销售属性至少添加一个属性值"));

    return;
  }
  callback();
};

const SpuRules = reactive<FormRules>({
  spuName: [{ required: true, message: "请输入SPU名称", trigger: "blur" }],
  tmId: [{ required: true, message: "请选择SPU品牌", trigger: "change" }],
  description: [{ required: true, message: "请上传SPU描述", trigger: "blur" }],
  spuImageList: [{ required: true, message: "请上传SPU图片" }],
  spuSaleAttrList: [
    {
      required: true,
      validator: spuSaleAttrListValidator,
      // message: "请上传SPU图片"
    },
  ],
});

// 上传图片最大限制
const MAX_LIMIT = 3;
const uploadBtnDisplay = computed(() => {
  return spuFormDate.spuImageList.length < MAX_LIMIT ? "inline-flex" : "none";
});
//添加销售属性
const selectedSaleAttr = ref("");
const AddSaleAttr = () => {
  const [id, name] = selectedSaleAttr.value.split(":");
  spuFormDate.spuSaleAttrList.push({
    baseSaleAttrId: +id,
    saleAttrName: name,
    spuSaleAttrValueList: [],
    isEdit: false,
  });
  selectedSaleAttr.value = "";
};
const filterSaleAttrList = computed(() => {
  return SaleAttrList.value.filter((baseSaleAttr) => {
    return !spuFormDate.spuSaleAttrList.some((saleAttr) => saleAttr.baseSaleAttrId === baseSaleAttr.id);
  });
});
//删除属性
const delSaleAttr = (index: number) => {
  spuFormDate.spuSaleAttrList.splice(index, 1);
};

//属性值,添加销售属性值
const AddSaleAttrValueName = ref("");
const AddSaleAttrValue = (row: SaveSpuSaleAttrItem) => {
  if (AddSaleAttrValueName.value) {
    row.spuSaleAttrValueList.push({
      baseSaleAttrId: row.baseSaleAttrId,
      saleAttrValueName: AddSaleAttrValueName.value,
    });
    AddSaleAttrValueName.value = "";
  }
  // 显示模式
  row.isEdit = false;
};

//删除属性值
const delSaleAttrValue = (row: SaveSpuSaleAttrItem, index: number) => {
  row.spuSaleAttrValueList.splice(index, 1);
};
// 点击显示模式的按钮进入编辑模式
const inputRef = ref();
const isEdit = async (row: SaveSpuSaleAttrItem) => {
  row.isEdit = true;
  await nextTick();
  inputRef.value.focus();
};

//取消,到spuList
const emit = defineEmits(["setIsShow"]);
const goSpuList = () => {
  emit("setIsShow", 1);
};
//保存,提交表单
const categoryStore = useCategoryStore();
const submitForm = async () => {
  await spuFromRef.value?.validate();
  await saveSpuApi({
    ...spuFormDate,
    spuImageList: spuFormDate.spuImageList.map((img) => {
      return {
        imgName: img.name,
        imgUrl: (img.response as any).data,
      };
    }),
    category3Id: categoryStore.category3Id as number,
  });
  ElMessage.success("添加SPU成功");

  goSpuList();
};
</script>

<style scoped>
.spu-card :deep(.el-upload) {
  display: v-bind(uploadBtnDisplay);
}
.spu-card {
  margin: 10px 0;
}
</style>
